package com.unlcn.ils.wms.web.controller.inbound;

import cn.huiyunche.commons.domain.ResultDTO;
import cn.huiyunche.commons.exception.BusinessException;
import com.unlcn.ils.wms.backend.service.inbound.WmsJMInboundService;
import com.unlcn.ils.wms.backend.util.BrowerEncodeingUtils;
import com.unlcn.ils.wms.base.businessDTO.inbound.AsnOrderDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * 君马入库业务处理-表现层
 *
 * @author user
 */
@Controller
@RequestMapping(value = "/jminbound")
@ResponseBody
public class WmsJMInboundController {

    private Logger logger = LoggerFactory.getLogger(WmsJMInboundController.class);

    private static final String filename = "ImportAsnTemplate.xls";

    @Autowired
    private WmsJMInboundService wmsJMInboundService;


    /**
     * asn导入功能
     * <p>
     * 2018-4-19 重构入库通知单数据 此新方法
     * </p>
     *
     * @param file    上传文件
     * @param request 请求
     * @return 返回值
     */
    @RequestMapping(value = "/importAsnByExcel", method = RequestMethod.POST)
    public ResultDTO<Object> importAsnByExcel(@RequestParam(value = "file") MultipartFile file,
                                              HttpServletRequest request) {
        logger.info("JMInboundController.importAsnByExcel param:{}", file);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "导入数据成功");
        try {
            String whCode = request.getHeader("whCode");
            String userId = request.getHeader("userId");
            wmsJMInboundService.saveImportAsnByExcel(whCode, userId, file);
        } catch (BusinessException e) {
            logger.error("JMInboundController.importAsnByExcel error: {}", e);
            result.setMessage(e.getMessage());
            result.setSuccess(false);
            //throw new BusinessException(e.getMessage());
        } catch (Exception ex) {
            logger.error("JMInboundController.importAsnByExcel error: {}", ex);
            result.setMessage("导入系统异常");
            result.setSuccess(false);
            result.setData(null);
            //throw new BusinessException("导入系统异常");
        }
        return result;
    }

    /**
     * (增加wms_asn_temp 同步数据到入库通知单数据)
     * <p>
     * 2018-4-19 重构入库通知单数据 此新方法
     * </p>
     *
     * @return 返回值
     */
    @RequestMapping(value = "/syncASNToNotice", method = RequestMethod.POST)
    public ResultDTO<Object> syncWmsAsnTempToNotice() {
        ResultDTO<Object> result = new ResultDTO<>(true, null, "数据成功");
        try {
            wmsJMInboundService.updateSyncWmsAsnTempToNotice();
            wmsJMInboundService.updateSyncTmsOrderToNotice();
        } catch (BusinessException e) {
            logger.error("JMInboundController.importAsnByExcel error: {}", e);
            result.setMessage(e.getMessage());
            result.setSuccess(false);
            //throw new BusinessException(e.getMessage());
        } catch (Exception ex) {
            logger.error("JMInboundController.importAsnByExcel error: {}", ex);
            result.setMessage("导入系统异常");
            result.setSuccess(false);
            result.setData(null);
            //throw new BusinessException("导入系统异常");
        }
        return result;
    }


    /**
     * asn导入功能
     * <p>
     * 2018-4-19 重构入库通知单数据 此方法过时 新方法{@link WmsJMInboundController#importAsnByExcel}
     * </p>
     *
     * @param file    上传文件
     * @param request 请求
     * @return 返回值
     */
    @RequestMapping(value = "/importAsnByExcel-old", method = RequestMethod.POST)
    @Deprecated
    public ResultDTO<Object> importAsnByExcelOld(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
        logger.info("JMInboundController.importAsnByExcelOld param:{}", file);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "导入数据成功");
        try {
            String whCode = request.getHeader("whCode");
            String userId = request.getHeader("userId");
            wmsJMInboundService.saveImportAsnByExcelOld(whCode, userId, file);
        } catch (BusinessException e) {
            logger.error("JMInboundController.importAsnByExcelOld error: {}", e);
            result.setMessage(e.getMessage());
            result.setSuccess(false);
            //throw new BusinessException(e.getMessage());
        } catch (Exception ex) {
            logger.error("JMInboundController.importAsnByExcelOld error: {}", ex);
            result.setMessage("导入系统异常");
            result.setSuccess(false);
            result.setData(null);
            //throw new BusinessException("导入系统异常");
        }
        return result;
    }

    /**
     * asn模板下载
     *
     * @param response 响应体
     * @param request  请求体
     * @return 返回值
     */
    @RequestMapping(value = "/downloadTemplate", method = RequestMethod.GET)
    public ResultDTO<Object> downloadTemplate(HttpServletRequest request, HttpServletResponse response) {
        logger.info("JMInboundController.downloadTemplate param:{}.");
        ResultDTO<Object> result = new ResultDTO<>(true, null, "下载模板成功");
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //String path = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "excel";
            String path = request.getSession().getServletContext().getRealPath("/WEB-INF/classes/excel") + "/" + filename;
            path = path.replace("\\", "/");
            //String filePath=path+"/excel/"+filename;
            File file = new File(path);
            //以下载方式打开
            //D:\git_rep\wms-extra\ils-wms-extra-web\target\ils-wms-extra-web\WEB-INF\classes\excel
            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", BrowerEncodeingUtils.getContentDisposition(file.getName(), request));
            //response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            byte[] bytes = new byte[2048];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
        } catch (IOException ie) {
            logger.error("JMInboundController.downloadTemplate param:{}.", ie);
            result.setMessage(ie.getMessage());
            result.setSuccess(false);
            result.setData(null);
            //throw new BusinessException("读取文件错误");
        } catch (Exception ex) {
            logger.error("JMInboundController.downloadTemplate error: {}", ex);
            result.setMessage(ex.getMessage());
            result.setSuccess(false);
            result.setData(null);
            //throw new BusinessException("系统异常");
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    logger.error("JMInboundController.closeOutputStream error: {}", e);
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("JMInboundController.closeInputStream error: {}", e);
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


    /**
     * asn打印二维码
     * <p>
     * 2018-4-20 入库通知单重构,此方法 新方法
     * </p>
     *
     * @return 返回值
     */
    @RequestMapping(value = "/printAsnQrCode", method = RequestMethod.POST)
    public ResultDTO<List<Object>> printAsnQrCode(HttpServletRequest request, @RequestBody String[] atId) {
        logger.info("JMInboundController.printAsnQrCode param:{}.");
        ResultDTO<List<Object>> result = new ResultDTO<>(true, null, "打印二维码成功");
        try {
            String whCode = request.getHeader("whCode");
            result.setData(wmsJMInboundService.getAsnQrCode(whCode, atId));
        } catch (BusinessException be) {
            logger.error("TmsInspectController.printAsnQrCode BusinessException: {}", be);
            result.setMessage(be.getMessage());
            result.setSuccess(false);
            result.setData(null);
        } catch (Exception e) {
            logger.error("TmsInspectController.printAsnQrCodeOld error: {}", e);
            result.setMessage("系统异常");
            result.setSuccess(false);
            result.setData(null);
        }
        return result;
    }

    /**
     * asn打印二维码
     * <p>
     * 2018-4-20 入库通知单重构,重写此方法 新方法{@link WmsJMInboundController#printAsnQrCode}
     * </p>
     *
     * @return 返回值
     */
    @RequestMapping(value = "/printAsnQrCode-old", method = RequestMethod.POST)
    @Deprecated
    public ResultDTO<List<Object>> printAsnQrCodeOld(HttpServletRequest request, @RequestBody String[] atId) {
        logger.info("JMInboundController.printAsnQrCodeOld param:{}.");
        ResultDTO<List<Object>> result = new ResultDTO<>(true, null, "打印二维码成功");
        try {
            String whCode = request.getHeader("whCode");
            result.setData(wmsJMInboundService.getAsnQrCodeOld(whCode, atId));
        } catch (BusinessException be) {
            result.setMessage(be.getMessage());
            result.setSuccess(false);
            result.setData(null);
            logger.error("TmsInspectController.printAsnQrCodeOld BusinessException: {}", be);
            //throw new BusinessException(e.getMessage());
        } catch (Exception e) {
            result.setMessage("系统异常");
            result.setSuccess(false);
            result.setData(null);
            logger.error("TmsInspectController.printAsnQrCodeOld error: {}", e);
            //throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * <p>
     * 使用inbounderOrder里面的收货质检--君马
     * 君马库收获质检并分配库位 推送库位到app 推送退车信息到sap
     * </p>
     */
    @RequestMapping(value = "/inspectQuality/{userId}", method = RequestMethod.POST)
    public ResultDTO<Object> printAsnQrCode(@RequestBody String vin, @PathVariable String userId) {
        logger.info("JMInboundController.printAsnQrCode param:{}.");
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "生成库位成功");
        if (StringUtils.isBlank(vin)) {
            throw new BusinessException("传入车架号为空!");
        }
        //回车字符替换
        if (vin.endsWith("\n")) {
            vin = vin.replaceAll("\n", "");
        }
        try {
            AsnOrderDTO result = wmsJMInboundService.saveAllcationByExtra(vin, userId);
            resultDTO.setSuccess(true);
            resultDTO.setMessage("生成库位成功");
            resultDTO.setData(result);
            return resultDTO;
        } catch (Exception ex) {
            resultDTO.setSuccess(false);
            resultDTO.setMessage(ex.getMessage());
            return resultDTO;
        }
    }

}
